const app = getApp()
const FormData=require("../../utils/wx-formdata/formData.js")
import {address} from "../../request/api.js"
// 导入外部函数
import {
  writeBLECharacteristicValue,
  notifyBLECharacteristicValueChange
} from "../../request/blue"
import codes from "../../request/funcCode"
import {
  stringToBytes,
  getNowTime
} from "../../utils/utils"
import debounce from "../../utils/debounce"
import throttle from "../../utils/throttle"
Page({
  data: {
    // code: "", // 功能码
    inputText: "", // 输入框信息
    progressInfo: "实时速度", // 进度条信息
    showBox: false, // 是否显示下部输入框
    ProgressValue: 5, // 进度条值
    receiveText: '', // 接收值
    receiveData:"", // 展示值
    receiveTestText:"", //下方发送数据值
    receiveArry: [],
    name: '设备未连接', // 设备名称
    connectedDeviceId: '', // 设备ID
    serviceId: "55535343-FE7D-4AE5-8FA9-9FAFD205E455", //可写的服务ID
    characteristics: '49535343-8841-43F4-A8D4-ECBE34729BB3', //可写的characteristics ID
    connected: true, // 是否连接蓝牙标志位
    errorText:"",
    code:""
  },
  bindInput: function (e) {
    this.setData({
      inputText: e.detail.value
    })
    console.log(e.detail.value)
  },
  // 显示输入栏`
  ShowBox() {
    var show = this.data.showBox
    this.setData({
      showBox: !show
    })
    // console.log(this.data.showBox);
  },
  // 进度条停止函数
  SliderChanged(e) {
    let that = this
    let provalue = e.detail.value // 获取进度条数据
    let {
      code,
      progressInfo
    } = that.CompareProvalue(provalue)

    // 数据回显
    that.setData({
      progressInfo: progressInfo
    })
    // 发送数据
    that.WriteData(code)
  },
  // 比较滑动条得值
  CompareProvalue(provalue) {
    // let code = ""
    let {code}=this
    let progressInfo = ""
    // console.log(provalue);
    // 根据进度条进度获取功能码和速度信息
    switch (provalue <= 100 && provalue >= 0) {
      case provalue > 0 && provalue < 16:
        code = codes.speed1
        progressInfo = "1"
        break;
      case provalue >= 16 && provalue <= 32:
        code = codes.speed2
        progressInfo = "2"
        break;
      case provalue > 32 && provalue < 48:
        code = codes.speed3
        progressInfo = "3"
        break;
      case provalue >= 48 && provalue < 64:
        code = codes.speed4
        progressInfo = "4"
        break;
      case provalue >= 64 && provalue < 80:
        code = codes.speed5
        progressInfo = "5"
        break;
      case provalue >= 80 && provalue <= 100:
        code = codes.speed6
        progressInfo = "6"
        break;
      default: progressInfo="停止",code=codes.stop
    }
    this.setData({
        code:code
    })
    return {
      code,
      progressInfo
    }
  },
  // 滑动条改变时触发函数
  SliderChanging(e) {
    // 滑动时改变展示信息而不发送数据
    let {
      progressInfo
    } = this.CompareProvalue(e.detail.value)
    this.setData({
      progressInfo: progressInfo
    })
  },
  // 功能码发送函数
  SendCode: function (e) {
    var that = this
    if (that.data.connected) {
      let code = e.currentTarget.dataset.code
    //   console.log("code", e.currentTarget.dataset.code);
      this.WriteData(code)
    } else {
      wx.showModal({
        title: '提示',
        content: '蓝牙已断开',
        showCancel: false,
        success: function (res) {
          that.setData({
            searching: false
          })
        }
      })
    }
  },
  // 上下左右按钮点击事件
  // debounce防抖控制多次点击时只执行最后一次(500毫秒执行一次)
  Control:debounce(function(e){
    var that = this
    // console.log(this);
    let {code}=this
    let pos = e.currentTarget.dataset.pos // 获取点击嘚按钮
    // console.log(pos);
    this.setData({
      isActive:pos
    })
    // 根据按钮决定功能码
    switch (pos) {
      case 'up':
        code = codes.speed2
        that.setData({
          ProgressValue:20,
          progressInfo:"前进2"
        })
        break;
      case 'left':
        if(code)
        that.WriteData(code)
        else{
            that.WriteData(codes.speed1)
        }
        setTimeout(()=>{
            that.WriteData(codes.left)
            return
        },100)
        break;
      case 'right':
        if(code)
        that.WriteData(code)
        else{
            that.WriteData(codes.speed1)
        }
        setTimeout(()=>{
            that.WriteData(codes.right)
            return
        },100)
        break;
      case 'stop':
        that.setData({
          ProgressValue:0,
          progressInfo:'停'
        })
        code = codes.stop
        break;
    }
    if(code)
    that.setData({
        code:code
    })
    // 写入数据
    that.WriteData(code)

  },500,{
    leading:true,
    trailing:false
  }),
  // 写数据函数
  async WriteData(code) {
    var that = this
    console.log("writeCode", code);
    let date=getNowTime()
    let str=that.data.inputText+date+code+"\r\n"
    that.setData({
        inputText:str
    })
    
    // 字符串转换
    let buffer = stringToBytes(code)
    try {
      // 异步将数据写入蓝牙中
      await writeBLECharacteristicValue(that.data.connectedDeviceId,
      that.data.serviceId,
      that.data.characteristics,
      buffer)
    } catch (error) {
      console.log(error);
    }
  },
  async setDeviceName(){
      await wx.request({
        url: `${address}/wxuser/setDeviceName`,
        method:"GET",
        data:{
            'wxid':app.globalData.userInfo._id,
            'deviceName':this.data.name
        },
        // },
        success(res){
            console.log(res);
        },
        fail(res){
            console.log(res);
        },
      })
  },
  async setDeviceStatus(status){
    await wx.request({
        url: `${address}/wxuser/setDeviceStatus`,
        method:"GET",
        data:{
            'wxid':app.globalData.userInfo._id,
            'status':status
        },
        // },
        success(res){
            console.log(res);
        },
        fail(res){
            console.log(res);
        },
      })
  },
  onLoad: function (options) {
    var that = this
    console.log(options);
    that.setData({
      name: options.name,
      connectedDeviceId: options.connectedDeviceId
    })
    let deviceId=wx.getStorageSync('deviceId')
    // setInterval(async function(e){
    //   console.log(that.data.characteristics);
    //   console.log(that.data.connectedDeviceId);
    //   wx.readBLECharacteristicValue({
    //     characteristicId: that.data.characteristics,
    //     deviceId: deviceId,
    //     serviceId: that.data.serviceId,
    //   })
    // },5000)

    wx.getBLEDeviceServices({
      deviceId: that.data.connectedDeviceId,
      success: function (res) {
        var all_UUID = res.services;
        var index_uuid = -1;
        var index_uuid_notify = -1;
        var UUID_lenght = all_UUID.length;
        //console.log("service:" + JSON.stringify(res))
        /* 遍历服务数组 */
        for (var index = 0; index < UUID_lenght; index++) {
          var ergodic_UUID = all_UUID[index].uuid; //取出服务里面的UUID
          /* 判断是否是我们需要的 55535343-FE7D-4AE5-8FA9-9FAFD205E455*/
          if (ergodic_UUID === '55535343-FE7D-4AE5-8FA9-9FAFD205E455') {
            index_uuid = index;
          };
          /* 判断是否是我们需要的 5833FF01-9B8B-5191-6142-22A4536EF123 */
          if ("5833FF01-9B8B-5191-6142-22A4536EF123" === ergodic_UUID) {
            index_uuid_notify = index;
          };
        };
        // if (index_uuid == -1 && index_uuid_notify == -1) {
        //   wx.showModal({
        //     title: '提示',
        //     content: '非我方出售的设备',
        //     showCancel: false,
        //     success: function (res) {
        //       that.setData({
        //         searching: false
        //       })
        //     }
        //   })
        // }
        wx.notifyBLECharacteristicValueChange({
          state: true,
          deviceId: options.connectedDeviceId,
          serviceId: that.data.serviceId,
          characteristicId: "49535343-1E4D-4BD9-BA61-23C647249616",
          success: function (res) {
            console.log('启用notify成功',res.errMsg)
          },
          fail(res) {
            console.log(res)
          }
        })
      }
    })
    wx.onBLEConnectionStateChange(function (res) {
      console.log(res.connected)
      that.setData({
        connected: res.connected
      })
    })
    wx.onBLECharacteristicValueChange(function (res) {
      console.log('接收到数据：' + app.buf2string(res.value))
      // var time = that.getNowTime()
      that.setData({
        receiveData: app.buf2string(res.value),
        receiveTestText:app.buf2string(res.value)
      })
      let retext=that.data.receiveData.split("")
      console.log(retext);
      if(retext[0]=='C'&&retext[1]=='C'&&retext[2]=='W'){
        console.log(11);
        that.setData({
          receiveText:that.data.receiveText+"设备异常"+that.data.receiveData+"\n"
        })
      }
    })
    console.log('nowname',this.data.name);
    this.setDeviceName()
    this.setDeviceStatus(1)
    console.log(app.globalData.userInfo)
  },
  onUnload: function () {
    wx.closeBLEConnection({
      deviceId: this.data.connectedDeviceId,
      success: function (res) {},
    })
    this.setDeviceStatus(0)
  },
  SendCleanTap: function () {
    this.setData({
      inputText: ''
    })
  },

  RecvCleanTap: function () {
    this.setData({
      receiveTestText: ''
    })
  },
  SendValue: function (e) {
    this.setData({
      inputText: e.detail.value
    })
  },

})